<template>
  <div class="approval-tab-content">
    <div class="header-wrap">
      <h2>审核列表</h2>
    </div>

    <!-- 用 el-tabs 做三种状态的切换 -->
    <el-tabs @tab-click="handleTabChange" v-model="currentTab" type="card">
      <el-tab-pane label="未审核列表"  name="pending"  />
      <el-tab-pane label="已通过列表"  name="approved" />
      <el-tab-pane label="未通过列表"  name="rejected" />
    </el-tabs>

    <!-- 用 el-table 展示 -->
    <el-table
      :data="filteredSubmissions"
      stripe
      style="width: 100%; margin-top: 16px"
      empty-text="暂无数据"
    >
      <el-table-column type="index" label="序号" width="60" align="center" />
      <el-table-column label="提交人" align="center">
        <template #default="scope">
          {{ scope.row.uploadName || scope.row.lawyerName || '未知提交人' }}
        </template>
      </el-table-column>
      <el-table-column label="提交时间">
        <template #default="scope">{{ formatDate(scope.row.submitTime) }}</template>
      </el-table-column>

      <!-- PDF -->
      <el-table-column label="PDF地址">
        <template #default="scope">
          <el-link
            type="primary"
            :underline="false"
            @click="downloadFile(scope.row.formFileUrl)"
          >
            下载PDF
          </el-link>
        </template>
      </el-table-column>

      <!-- 证件 -->
      <el-table-column label="证件地址">
        <template #default="scope">
          <div v-if="scope.row.documents && Object.keys(scope.row.documents).length">
            <div
              v-for="(doc, name) in scope.row.documents"
              :key="name"
              style="margin-bottom: 4px"
            >
              <el-link
                type="primary"
                :underline="false"
                @click="downloadFile(doc.url)"
              >
                {{ name }}
              </el-link>
            </div>
          </div>
        </template>
      </el-table-column>

      <!-- 状态 -->
      <el-table-column label="状态" width="100" align="center">
        <template #default="scope">
          <el-tag
            :type="
              scope.row.status === 'approved'
                ? 'success'
                : scope.row.status === 'rejected'
                ? 'danger'
                : 'info'
            "
          >
            {{
              scope.row.status === 'approved'
                ? '已通过'
                : scope.row.status === 'rejected'
                  ? '已拒绝'
                  : '待审核'
            }}
          </el-tag>
        </template>
      </el-table-column>

      <!-- 操作 -->
      <el-table-column label="操作" width="280" align="center">
        <template #default="scope">
          <template
            v-if="scope.row.status !== 'approved' && scope.row.status !== 'rejected'"
          >
            <el-button
              size="small"
              type="success"
              @click="confirmApproval(scope.row.id, true)"
            >
              通过
            </el-button>
            <el-button
              size="small"
              type="danger"
              @click="handleReject(scope.row.id)"
            >
              拒绝
            </el-button>
          </template>
          <span v-else class="action-record">
            {{
              scope.row.status === 'approved'
                ? '已通过审核'
                : `拒绝原因: ${scope.row.rejectReason || '无理由'}`
            }}
          </span>
        </template>
      </el-table-column>
    </el-table>

    <!-- 拒绝弹窗 -->
    <el-dialog
      v-model="showRejectReason"
      title="请输入拒绝原因"
      width="400"
      @close="()=>{rejectReason = '';currentSubmissionId=null;}"
    >
      <el-input
        v-model="rejectReason"
        type="textarea"
        :rows="4"
        placeholder="请说明拒绝原因..."
      />
      <template #footer>
        <el-button @click="showRejectReason = false">取消</el-button>
        <el-button type="primary" @click="submitReject">确认</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, computed } from 'vue';
import { ElMessage } from 'element-plus';
import instance from '@/service/index.js';

// 缓存相关
const CACHE_KEY = 'lawyer_approval_submissions';

const getCachedSubmissions = () => {
  const cacheStr = localStorage.getItem(CACHE_KEY);
  if (cacheStr) {
    try {
      return JSON.parse(cacheStr);
    } catch (e) {
      localStorage.removeItem(CACHE_KEY);
      return [];
    }
  }
  return [];
};

const setCachedSubmissions = (submissions) => {
  localStorage.setItem(CACHE_KEY, JSON.stringify(submissions));
};

const allSubmissions = ref(getCachedSubmissions());

// 标签切换状态：未审核(pending) 和 已通过(approved)
const currentTab = ref('pending');

// 根据当前标签筛选显示的记录
const filteredSubmissions = computed(() => {
  if (currentTab.value === 'approved') {
    // 已通过列表：只显示状态为已通过的记录
    return allSubmissions.value.filter(item => item.status === 'approved');
  }else if (currentTab.value === 'rejected') {
    return allSubmissions.value.filter(item => item.status === 'rejected');
  } else {
    return allSubmissions.value.filter(item => item.status !== 'approved' && item.status !== 'rejected');
  }

});

// 弹窗控制
const showRejectReason = ref(false);
const rejectReason = ref('');
const currentSubmissionId = ref(null);

// 获取Token
const getToken = () => {
  return sessionStorage.getItem("token") || "";
};

// 下载文件方法
const downloadFile = (fileName) => {
  if (!fileName) {
    ElMessage.error('文件名不存在');
    return;
  }

  const token = getToken();
  const fullUrl = `http://localhost:8888/api/submissions/files/download?fileName=${encodeURIComponent(fileName)}&token=${token}`;


  const xhr = new XMLHttpRequest();
  xhr.open('GET', fullUrl, true);
  xhr.setRequestHeader('Authorization', `Auth ${token}`);
  xhr.responseType = 'blob';

  xhr.onload = function() {
    if (xhr.status === 200) {
      if (xhr.response.size === 0) {
        ElMessage.error('文件内容为空（后端返回空流）');
        return;
      }

      const url = window.URL.createObjectURL(xhr.response);
      const a = document.createElement('a');
      a.href = url;
      a.download = fileName;
      document.body.appendChild(a);
      a.click();

      setTimeout(() => {
        document.body.removeChild(a);
        window.URL.revokeObjectURL(url);
      }, 100);
    } else {
      try {
        const reader = new FileReader();
        reader.onload = () => {
          const errorMsg = reader.result || `HTTP错误: ${xhr.status}`;
          ElMessage.error(`下载失败: ${errorMsg}`);
        };
        reader.readAsText(xhr.response);
      } catch (e) {
        ElMessage.error(`下载失败: HTTP状态码 ${xhr.status}`);
      }
    }
  };

  xhr.onerror = function() {
    ElMessage.error('网络错误，无法连接到服务器');
  };

  xhr.send();
};

// 获取后端待审核列表
const fetchPendingSubmissions = () => {

  instance.get('/api/submissions/pending')
    .then(response => {
      if (response && response.data && Array.isArray(response.data)) {
        const newPendingSubmissions = response.data.map(item => ({
          ...item,
          status: item.status || 'pending',
          rejectReason: item.rejectReason || ''
        }));

        // 去重合并
        const mergedSubmissions = [...allSubmissions.value];
        newPendingSubmissions.forEach(newSub => {
          const isExist = mergedSubmissions.some(existSub => existSub.id === newSub.id);
          if (!isExist) {
            mergedSubmissions.push(newSub);
          }
        });

        allSubmissions.value = mergedSubmissions;
        setCachedSubmissions(mergedSubmissions);
      } else {
        ElMessage.error('数据格式错误：不是数组');
      }
    })
    .catch(error => {
      ElMessage.error('获取待审核列表失败');
    });
};


// 处理标签切换事件
const handleTabChange = (tab) => {
  // tab 参数包含当前切换的标签信息
  console.log('切换到标签:', tab.name);
  // 可以在这里根据标签切换加载对应的数据
  // 例如：如果切换到已通过列表，可以重新请求最新数据
  if (tab.name === 'approved') {
    // fetchApprovedSubmissions();
  }
};

// 处理拒绝
const handleReject = (submissionId) => {
  currentSubmissionId.value = submissionId;
  showRejectReason.value = true;
};

// 确认审核通过 - 会自动从"未审核列表"移除并添加到"已通过列表"
const confirmApproval = (submissionId, isApproved) => {
  if (isApproved) {
    instance.put(`/api/submissions/${submissionId}/approve`)
      .then(() => {
        ElMessage.success('审核通过');

        // 更新本地记录状态
        const submission = allSubmissions.value.find(item => item.id === submissionId);
        if (submission) {
          submission.status = 'approved';
          setCachedSubmissions(allSubmissions.value);
        }
      })
      .catch(error => {
        ElMessage.error('操作失败: ' + (error.message || '未知错误'));
      });
  } else {
    handleReject(submissionId);
  }
};

// 提交拒绝
const submitReject = () => {
  if (!rejectReason.value.trim()) {
    ElMessage.error('请输入拒绝原因');
    return;
  }

  const token = getToken();
  const url = `/api/submissions/${currentSubmissionId.value}/reject?remark=${encodeURIComponent(rejectReason.value)}&token=${token}`;

  instance.put(url, null, {
    headers: { 'Authorization': `Auth ${token}` }
  }).then(() => {
    ElMessage.success('已拒绝该申请');

    const submission = allSubmissions.value.find(item => item.id === currentSubmissionId.value);
    if (submission) {
      submission.status = 'rejected';
      submission.rejectReason = rejectReason.value;
      setCachedSubmissions(allSubmissions.value);
    }

    showRejectReason.value = false;
    rejectReason.value = '';
  }).catch(error => {
    ElMessage.error('操作失败: ' + (error.message || '未知错误'));
  });
};

// // 清空缓存
// const clearCache = () => {
//   if (confirm('确定要清空所有历史审核记录吗？此操作不可恢复！')) {
//     allSubmissions.value = [];
//     setCachedSubmissions([]);
//     ElMessage.success('历史记录已清空');
//   }
// };

// 日期格式化
const formatDate = (dateStr) => {
  if (!dateStr) return '';
  const date = new Date(dateStr);
  return isNaN(date.getTime()) ? '日期格式错误' : date.toLocaleString();
};

// 组件加载时
onMounted(() => {
  fetchPendingSubmissions();
});
</script>

<style scoped>
/* 表头按钮和筛选标签布局 */
.header-wrap {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
  flex-wrap: wrap;
  gap: 10px;
}

/* 筛选标签样式 */
.filter-tabs {
  display: flex;
  gap: 10px;
}

.filter-tabs button {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  background: transparent;
  cursor: pointer;
  font-size: 14px;
}

.filter-tabs button.tab-active {
  background-color: #1890ff;
  color: white;
  border-color: #1890ff;
}

.clear-cache-btn {
  padding: 6px 12px;
  border: 1px solid #f5222d;
  border-radius: 4px;
  color: #f5222d;
  background: transparent;
  cursor: pointer;
  font-size: 12px;
}
.clear-cache-btn:hover {
  background-color: #fff2f0;
}

/* 其他样式不变 */
.approval-tab-content {
  margin-bottom: 40px;
  padding: 20px;
  background-color: white;
  border-radius: 8px;
  box-shadow: 0 2px 4px rgba(0,0,0,0.1);
}

.submissions-table th {
  background-color: #f5f4f4;
  border: 1px solid #eee;
  padding: 10px;
  text-align: left;
}
.submissions-table td {
  padding: 12px 8px;
  border: 1px solid #eee;
  vertical-align: middle;

}
.submissions-table tr:hover {
  background-color: #f9f9f9;
}

.index-center {
  text-align: center;
}

.status-tag {
  display: inline-block;
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}
.status-pending {
  background-color: #e6f7ff;
  color: #1890ff;
}
.status-approved {
  background-color: #f6ffed;
  color: #52c41a;
}
.status-rejected {
  background-color: #fff2f0;
  color: #f5222d;
}

.approve-btn, .reject-btn {
  padding: 6px 12px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  color: #fff;
}
.approve-btn {
  background-color: #90d369;
}
.reject-btn {
  background-color: #fc0a0a;
}

.action-record {
  font-size: 14px;
  color: #303133;
  background: none;
  border: none;
  letter-spacing: 0.3px;
}

.file-link, .doc-link {
  color: #4285f4;
  text-decoration: none;
  display: inline-block;
  margin-right: 4px;
}
.file-url, .doc-url {
  word-break: break-all;
  margin-top: 4px;
  font-size: 12px;
  color: #666;
}
.reject-modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background: rgba(0,0,0,0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}
.modal-content {
  background: white;
  padding: 20px;
  border-radius: 6px;
  width: 500px;
}
.modal-content textarea {
  width: 100%;
  height: 100px;
  margin: 15px 0;
  padding: 8px;
  border: 1px solid #ddd;
}
.modal-actions {
  display: flex;
  justify-content: flex-end;
  gap: 10px;
}
.modal-actions button {
  padding: 8px 16px;
  border: 1px solid #ddd;
  border-radius: 4px;
  cursor: pointer;
}
.modal-actions button:last-child {
  background: #db4437;
  color: white;
  border-color: #db4437;
}
</style>
